package xj.graph2d.encoder;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import xj.graph2d.AbstractEncoder;
import xj.graph2d.DrawCanvas;
import xj.graph2d.View;

public class ImageEncoder extends AbstractEncoder {

  public ImageEncoder() {
  }

  public ImageEncoder(String name, String fileExtension,
		      String fileDescription, 
		      int imageType, View view) {
    super(name, fileExtension, fileDescription, view);
    this.imageType = imageType;
  }

  public void setImageType(int imageType) {
    this.imageType = imageType;
  }

  @Override
  public void setImageType(String type) {
    if ("jpg".equals(type) || "jpeg".equals(type)) {
      imageTypeName = "jpeg";
      imageType = JPEG;
    } else if ("png".equals(type)) {
      imageTypeName = "png";
      imageType = PNG;
    } else {
      imageTypeName = null;
    }
  }

  @Override
  public void encode(String filename, Rectangle2D r) throws IOException {
    if (view != null) {
      DrawCanvas canvas = view.getCanvas();
      if (filename != null && 
	  imageTypeName != null && 
	  canvas != null && 
	  r != null) {
	int mw = (int) view.getMarginWidth();
	int mh = (int) view.getMarginHeight();
	int w = (int) r.getWidth() + 2 * mw;
	int h = (int) r.getHeight() + 2 * mw;

	BufferedImage image = new BufferedImage(w, h,
	    BufferedImage.TYPE_INT_RGB);
	Graphics2D g = (Graphics2D) image.getGraphics();
	setRenderingHints(g);
	Color bg = view.getBackgroundColor();
	g.setColor(bg);
	g.fillRect(0, 0, w, h);

	drawWaterMark(g, 0, 0, w, h);

	g.translate(-r.getX() + mw, -r.getY() + mh);
	view.paintCanvas(g, null, true); // draw all objects

	File file = new File(filename);
	ImageIO.write(image, imageTypeName, file);
      }
    }
  }

  protected int imageType;

  protected String imageTypeName;

}
